package cn.com.gas.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.com.common.constants.Constants;
import cn.com.common.result.DataResult;
import cn.com.gas.entity.GasMineExportEntity;
import cn.com.gas.entity.GasStationinfoEntity;
import cn.com.gas.entity.GasStaytimeResultEntity;
import cn.com.gas.service.GasMineExportService;
import cn.com.gas.service.GasStationinfoService;
import cn.com.gas.service.GasStaytimeResultService;
import cn.com.gas.vo.excel.GasStaytimeResultExcel;
import cn.com.system.service.DeptService;
import cn.com.system.service.impl.HttpSessionService;
import cn.com.util.TsBqUtils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.PostMapping;

import java.util.zip.ZipOutputStream;


/**
 * 加油明细
 *
 * @author shaochangyang
 * @email l2l84o7o5@live.com
 * @date 2024-03-24 01:14:06
 */
@Controller
@RequestMapping("/gas/staytime")
public class GasStaytimeResultController {
	@Autowired
	private GasStaytimeResultService gasStaytimeResultService;

	@Autowired
	private GasStationinfoService gasStationinfoService;

	@Autowired
	private DeptService deptService;

	@Autowired
	private GasMineExportService gasMineExportService;

	@Autowired
	private HttpSessionService httpSessionService;

	@Value("${file.path}")
	private String filePath;
	@Value("${file.url}")
	private String fileUrl;
	
	@ApiOperation(value = "查询分页数据")
	@PostMapping("/edit")
	// @RequiresPermissions("gasStaytimeResult:list")
	@ResponseBody
	public DataResult edit(@RequestBody GasStaytimeResultEntity gasStaytimeResult) throws ParseException {
		
		// 只修改金额
		String price = gasStaytimeResult.getPrice();
		
		if(TsBqUtils.isNull(price)){
			return DataResult.fail("price金额不能空！");
		}
		
		String id = gasStaytimeResult.getId();
		String messageDisappear = gasStaytimeResult.getMessageDisappear();
		
		LambdaQueryWrapper<GasStaytimeResultEntity> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.eq(GasStaytimeResultEntity::getId, id);
		queryWrapper.eq(GasStaytimeResultEntity::getMessageDisappear, messageDisappear);
		List<GasStaytimeResultEntity> list = gasStaytimeResultService.list(queryWrapper);
		if(TsBqUtils.isNotNull(list)){
			GasStaytimeResultEntity gasStaytimeResultEntity = list.get(0);
			gasStaytimeResultEntity.setPrice(price);
			
			LambdaQueryWrapper<GasStaytimeResultEntity> updateWrapper = Wrappers.lambdaQuery();
			updateWrapper.eq(GasStaytimeResultEntity::getId, id);
			updateWrapper.eq(GasStaytimeResultEntity::getMessageDisappear, messageDisappear);
			gasStaytimeResultService.update(gasStaytimeResultEntity, updateWrapper);
			
			return DataResult.success();
		}else{
			
			return DataResult.fail("通过id:" + id+",messageDisappear" + messageDisappear + "未查询到！");
		}
		
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@ApiOperation(value = "查询分页数据")
	@PostMapping("/list")
	// @RequiresPermissions("gasStaytimeResult:list")
	@ResponseBody
	public DataResult findListByPage(@RequestBody GasStaytimeResultEntity gasStaytimeResult) throws ParseException {

		String currentDeptId = httpSessionService.getCurrentDeptId();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		String deptId = gasStaytimeResult.getDeptId();
		String stationName = gasStaytimeResult.getStationName();

		// 查询加油站
		LambdaQueryWrapper<GasStationinfoEntity> queryWrapperStationinfo = Wrappers.lambdaQuery();
		if (TsBqUtils.isNotNull(deptId)) {
			queryWrapperStationinfo.eq(GasStationinfoEntity::getType, "group");
			queryWrapperStationinfo.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			queryWrapperStationinfo.eq(GasStationinfoEntity::getTaxorgcode, deptId);

		} else {
			if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 县区局
				queryWrapperStationinfo.eq(GasStationinfoEntity::getType, "group");
				queryWrapperStationinfo.eq(GasStationinfoEntity::getIsAnalyse, "Y");
				queryWrapperStationinfo.eq(GasStationinfoEntity::getTaxorgcode, currentDeptId);

			} else if (Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 市局
				queryWrapperStationinfo.eq(GasStationinfoEntity::getType, "group");
				queryWrapperStationinfo.eq(GasStationinfoEntity::getIsAnalyse, "Y");
				queryWrapperStationinfo.like(GasStationinfoEntity::getTaxorgcode, currentDeptId.substring(0, 5));

			} else {
				// 省局
				queryWrapperStationinfo.eq(GasStationinfoEntity::getType, "group");
				queryWrapperStationinfo.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			}
		}

		if (TsBqUtils.isNotNull(stationName)) {
			queryWrapperStationinfo.like(GasStationinfoEntity::getName, stationName);
		}

		// queryWrapperStationinfo.eq(GasStationinfoEntity::getPid,
		// "5c8baa4b-081f-41aa-a549-2235b786c7c7"); // 信都区
		// queryWrapperStationinfo.eq(GasStationinfoEntity::getType, "group");
		// queryWrapperStationinfo.eq(GasStationinfoEntity::getIsAnalyse, "Y");

		List<GasStationinfoEntity> listGasStationinfo = gasStationinfoService.list(queryWrapperStationinfo);
		List<String> stationinfoIdList = new ArrayList<>();
		for (GasStationinfoEntity stationinfo : listGasStationinfo) {
			String stationinfoId = stationinfo.getId();
			stationinfoIdList.add(stationinfoId);
		}
		// 查询加油站下面的摄像头
		// LambdaQueryWrapper<GasStationinfoEntity> queryWrapperCam =
		// Wrappers.lambdaQuery();
		// queryWrapperCam.in(GasStationinfoEntity::getPid, stationinfoIdList);
		// queryWrapperCam.eq(GasStationinfoEntity::getType, "cam");
		// List<GasStationinfoEntity> camList =
		// gasStationinfoService.list(queryWrapperCam);
		// List<String> camIdList = new ArrayList<>();
		// for (GasStationinfoEntity caminfo : camList) {
		// String id = caminfo.getId();
		// camIdList.add(id);
		// }

		// 查询区域 server_area
		// LambdaQueryWrapper<GasServerAreaEntity> areaQueryWrapper =
		// Wrappers.lambdaQuery();
		// areaQueryWrapper.in(GasServerAreaEntity::getCamid, camIdList);
		// List<GasServerAreaEntity> serverAreaList =
		// gasServerAreaService.list(areaQueryWrapper);

		// List<String> areaNumberList = new ArrayList<>();
		// List<String> serverChannelList = new ArrayList<>();
		// List<String> serverIdList = new ArrayList<>();

		// for (GasServerAreaEntity serverArea : serverAreaList) {
		// String areaNumber = serverArea.getAreaNumber();
		// String serverChannel = serverArea.getServerChannel();
		// String serverId = serverArea.getServerId();

		// areaNumberList.add(areaNumber);
		// serverChannelList.add(serverChannel);
		// serverIdList.add(serverId);
		// }

		// 查询渠道 server
		// LambdaQueryWrapper<GasServerChannelEntity> serverQueryWrapper =
		// Wrappers.lambdaQuery();
		// serverQueryWrapper.in(GasServerChannelEntity::getId, serverIdList);
		// List<GasServerChannelEntity> serverList =
		// gasServerChannelService.list(serverQueryWrapper);
		// List<String> listTopic = new ArrayList<>();
		// for (GasServerChannelEntity server : serverList) {
		// String topic = server.getTopic();
		// listTopic.add(topic);

		// }
		if (TsBqUtils.isNotNull(stationinfoIdList)) {
			Page page = new Page(gasStaytimeResult.getPage(), gasStaytimeResult.getLimit());
			LambdaQueryWrapper<GasStaytimeResultEntity> queryWrapper = Wrappers.lambdaQuery();
			// 查询条件示例
			String messageMsegtype = gasStaytimeResult.getMessageMsegtype();

			if (!TsBqUtils.isNull(gasStaytimeResult.getCreateTimeStart())) {
				queryWrapper.ge(GasStaytimeResultEntity::getMessageDisappear,
						sdf.parse(gasStaytimeResult.getCreateTimeStart() + " 00:00:00"));
			}else{
				return DataResult.success("start-MessageDisappear不能为空！");
			}
			
			if (!TsBqUtils.isNull(gasStaytimeResult.getCreateTimeEnd())) {
				queryWrapper.le(GasStaytimeResultEntity::getMessageDisappear,
						sdf.parse(gasStaytimeResult.getCreateTimeEnd() + " 23:59:59"));
			}else{
				return DataResult.success("end-MessageDisappear不能为空！");
			}

			if (!StringUtils.isEmpty(messageMsegtype)) {
				queryWrapper.eq(GasStaytimeResultEntity::getMessageMsegtype, messageMsegtype);
			}

			queryWrapper.in(GasStaytimeResultEntity::getStationId, stationinfoIdList);
			queryWrapper.orderByDesc(GasStaytimeResultEntity::getMessageDisappear);

			IPage<GasStaytimeResultEntity> iPage = gasStaytimeResultService.page(page, queryWrapper);
			List<GasStaytimeResultEntity> records = iPage.getRecords();
			for (GasStaytimeResultEntity staytime : records) {
				GasStationinfoEntity gasStationinfo = gasStationinfoService.getById(staytime.getStationId());

				staytime.setStation(TsBqUtils.handleEndBeforeParentheses(gasStationinfo.getName()));
				String taxorgcode = gasStationinfo.getTaxorgcode();
				String taxpayerCode = gasStationinfo.getTaxpayerCode();
				if (TsBqUtils.isNotNull(taxorgcode)) {
					String taxorgname = deptService.getById(taxorgcode).getName();
					staytime.setDeptName(taxorgname);
				}

				staytime.setTaxpayerCode(taxpayerCode);

				// 原来获取加油站信息，现在已经取到加油站ID，不使用原来的方法了
				/*
				 * String messageChannel = staytime.getMessageChannel(); String
				 * messageAreanumber = staytime.getMessageAreanumber();
				 * 
				 * String fromTopic = staytime.getFromTopic();
				 * 
				 * LambdaQueryWrapper<GasServerChannelEntity>
				 * serverChannelQueryWrapper = Wrappers.lambdaQuery();
				 * 
				 * serverChannelQueryWrapper.eq(GasServerChannelEntity::
				 * getTopic, fromTopic);
				 * 
				 * 
				 * List<GasServerChannelEntity> gasServerChannelList =
				 * gasServerChannelService.list(serverChannelQueryWrapper);
				 * 
				 * if(TsBqUtils.isNotNull(gasServerChannelList)){
				 * 
				 * GasServerChannelEntity serverChannel =
				 * gasServerChannelList.get(0); String gasServerId =
				 * serverChannel.getId();
				 * 
				 * LambdaQueryWrapper<GasServerAreaEntity>
				 * serverAreaQueryWrapper = Wrappers.lambdaQuery();
				 * 
				 * serverAreaQueryWrapper.eq(GasServerAreaEntity::
				 * getServerChannel, messageChannel);
				 * serverAreaQueryWrapper.eq(GasServerAreaEntity::getAreaNumber,
				 * messageAreanumber);
				 * serverAreaQueryWrapper.eq(GasServerAreaEntity::getServerId,
				 * gasServerId);
				 * 
				 * List<GasServerAreaEntity> list =
				 * gasServerAreaService.list(serverAreaQueryWrapper);
				 * 
				 * if(TsBqUtils.isNotNull(list)){ GasServerAreaEntity
				 * gasServerAreaEntity = list.get(0); String camid =
				 * gasServerAreaEntity.getCamid();
				 * if(TsBqUtils.isNotNull(camid)){ GasStationinfoEntity
				 * stationinfo = gasStationinfoService.getById(camid);
				 * if(TsBqUtils.isNotNull(stationinfo)){ String pid =
				 * stationinfo.getPid(); GasStationinfoEntity stationinfo1 =
				 * gasStationinfoService.getById(pid);
				 * if(TsBqUtils.isNotNull(stationinfo1)){
				 * 
				 * staytime.setStation(TsBqUtils.handleEndBeforeParentheses(
				 * stationinfo1.getName())); }else{
				 * staytime.setStation("未匹配到加油站(stationinfo1)"); } }else{
				 * staytime.setStation("未匹配到加油站(stationinfo)"); } }else{
				 * staytime.setStation("未匹配到加油站(camid)"); } }else{
				 * staytime.setStation("未匹配到加油站(GasServerArea)"); }
				 * 
				 * }else{ staytime.setStation("未匹配到加油站(GasServer)");
				 * 
				 * }
				 */

			}

			return DataResult.success(iPage);
		} else {
			return DataResult.fail("暂无加油站数据");
		}

	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@ApiOperation(value = "加油站列表下级-明细信息")
	@PostMapping("/list1")
	// @RequiresPermissions("gasStaytimeResult:list")
	@ResponseBody
	public DataResult findListByPage1(@RequestBody GasStaytimeResultEntity gasStaytimeResult) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		String stationId = gasStaytimeResult.getStationId();

		if (TsBqUtils.isNull(stationId)) {

			return DataResult.fail("入参stationId为NULL");
		}

		GasStationinfoEntity gasStationinfoEntity = gasStationinfoService.getById(stationId);
		String gasStationinfoName = gasStationinfoEntity.getName();

		Page page = new Page(gasStaytimeResult.getPage(), gasStaytimeResult.getLimit());

		LambdaQueryWrapper<GasStaytimeResultEntity> queryWrapper = Wrappers.lambdaQuery();

		if (!TsBqUtils.isNull(gasStaytimeResult.getCreateTimeStart())) {
			queryWrapper.ge(GasStaytimeResultEntity::getMessageDisappear,
					sdf.parse(gasStaytimeResult.getCreateTimeStart() + " 00:00:00"));
		}else{
			return DataResult.success("start-MessageDisappear不能为空！");
		}
		
		if (!TsBqUtils.isNull(gasStaytimeResult.getCreateTimeEnd())) {
			queryWrapper.le(GasStaytimeResultEntity::getMessageDisappear,
					sdf.parse(gasStaytimeResult.getCreateTimeEnd() + " 23:59:59"));
		}else{
			return DataResult.success("end-MessageDisappear不能为空！");
		}

		
		String messageMsegtype = gasStaytimeResult.getMessageMsegtype();
		if (!StringUtils.isEmpty(messageMsegtype)) {
			queryWrapper.eq(GasStaytimeResultEntity::getMessageMsegtype, messageMsegtype);
		}

		queryWrapper.in(GasStaytimeResultEntity::getStationId, stationId);
		queryWrapper.orderByDesc(GasStaytimeResultEntity::getMessageDisappear);
		IPage<GasStaytimeResultEntity> iPage = gasStaytimeResultService.page(page, queryWrapper);
		List<GasStaytimeResultEntity> records = iPage.getRecords();
		for (GasStaytimeResultEntity gasStaytimeResultEntity : records) {
			gasStaytimeResultEntity.setStation(TsBqUtils.handleEndBeforeParentheses(gasStationinfoName));
		}

		return DataResult.success(iPage);

	}

	@PostMapping("/exportData")
	@ResponseBody
	public DataResult exportData(@RequestBody GasStaytimeResultEntity gasStaytimeResult)
			throws java.io.IOException, ParseException {
		
		if (TsBqUtils.isNull(gasStaytimeResult.getCreateTimeStart())) {
			return DataResult.success("start-MessageDisappear不能为空！");
		}
		
		if (TsBqUtils.isNull(gasStaytimeResult.getCreateTimeEnd())) {
			return DataResult.success("end-MessageDisappear不能为空！");
		}
		
		String currentDeptId = httpSessionService.getCurrentDeptId();
		String currentUserId = httpSessionService.getCurrentUserId();

		// 插入gas_mine_export表
		GasMineExportEntity mineExportEntity = new GasMineExportEntity();
		String uuid = TsBqUtils.getUUID();
		mineExportEntity.setId(uuid);
		mineExportEntity.setModule("车流记录");

		mineExportEntity.setDeleted(Constants.DATA_NOT_DELETED);
		mineExportEntity.setCreateTime(new Date());
		mineExportEntity.setCreateId(currentUserId);
		mineExportEntity.setCreateTaxorgcode(currentDeptId);

		gasMineExportService.save(mineExportEntity);
		new Thread(() -> {
			try {
				System.out.println("睡眠前");
				Thread.sleep(20000);// 休眠时间设置为10000毫秒（10秒）
				System.out.println("睡眠后");
				asynExportData(gasStaytimeResult, uuid, currentDeptId);

			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}).start();

		return DataResult.success("稍后请在【我的导出】进行下载导出内容！");
	}

	private void asynExportData(GasStaytimeResultEntity gasStaytimeResult, String uuid, String currentDeptId)
			throws ParseException {

		GasMineExportEntity gasMineExportEntity = gasMineExportService.getById(uuid);
		// String description = "";
		// String currentDeptId = httpSessionService.getCurrentDeptId();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		String deptId = gasStaytimeResult.getDeptId();
		String stationName = gasStaytimeResult.getStationName();

		// 查询加油站
		LambdaQueryWrapper<GasStationinfoEntity> queryWrapperStationinfo = Wrappers.lambdaQuery();
		if (TsBqUtils.isNotNull(deptId)) {
			queryWrapperStationinfo.eq(GasStationinfoEntity::getType, "group");
			queryWrapperStationinfo.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			queryWrapperStationinfo.eq(GasStationinfoEntity::getTaxorgcode, deptId);

		} else {
			if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 县区局
				queryWrapperStationinfo.eq(GasStationinfoEntity::getType, "group");
				queryWrapperStationinfo.eq(GasStationinfoEntity::getIsAnalyse, "Y");
				queryWrapperStationinfo.eq(GasStationinfoEntity::getTaxorgcode, currentDeptId);

			} else if (Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 市局
				queryWrapperStationinfo.eq(GasStationinfoEntity::getType, "group");
				queryWrapperStationinfo.eq(GasStationinfoEntity::getIsAnalyse, "Y");
				queryWrapperStationinfo.like(GasStationinfoEntity::getTaxorgcode, currentDeptId.substring(0, 5));
			} else {
				// 省局
			}
		}

		if (TsBqUtils.isNotNull(stationName)) {
			queryWrapperStationinfo.like(GasStationinfoEntity::getName, stationName);
		}

		List<GasStationinfoEntity> listGasStationinfo = gasStationinfoService.list(queryWrapperStationinfo);
		List<String> stationinfoIdList = new ArrayList<>();
		for (GasStationinfoEntity stationinfo : listGasStationinfo) {
			String stationinfoId = stationinfo.getId();
			stationinfoIdList.add(stationinfoId);
		}

		if (TsBqUtils.isNotNull(stationinfoIdList)) {
			LambdaQueryWrapper<GasStaytimeResultEntity> queryWrapper = Wrappers.lambdaQuery();
			// 查询条件示例
			String messageMsegtype = gasStaytimeResult.getMessageMsegtype();

			if (!TsBqUtils.isNull(gasStaytimeResult.getCreateTimeStart())) {
				queryWrapper.ge(GasStaytimeResultEntity::getMessageDisappear,
						sdf.parse(gasStaytimeResult.getCreateTimeStart() + " 00:00:00"));
			}else{
				// return DataResult.success("end-MessageDisappear不能为空！");
				
			}
			
			if (!TsBqUtils.isNull(gasStaytimeResult.getCreateTimeEnd())) {
				queryWrapper.le(GasStaytimeResultEntity::getMessageDisappear,
						sdf.parse(gasStaytimeResult.getCreateTimeEnd() + " 23:59:59"));
			}else{
				// return DataResult.success("end-MessageDisappear不能为空！");
				
			}

			if (!StringUtils.isEmpty(messageMsegtype)) {
				queryWrapper.eq(GasStaytimeResultEntity::getMessageMsegtype, messageMsegtype);
			}

			queryWrapper.in(GasStaytimeResultEntity::getStationId, stationinfoIdList);
			queryWrapper.orderByDesc(GasStaytimeResultEntity::getMessageDisappear);

			List<GasStaytimeResultEntity> records = gasStaytimeResultService.list(queryWrapper);

			for (GasStaytimeResultEntity staytime : records) {
				GasStationinfoEntity gasStationinfo = gasStationinfoService.getById(staytime.getStationId());

				staytime.setStation(TsBqUtils.handleEndBeforeParentheses(gasStationinfo.getName()));
				String taxorgcode = gasStationinfo.getTaxorgcode();

				if (TsBqUtils.isNotNull(taxorgcode)) {
					String taxorgname = deptService.getById(taxorgcode).getName();
					staytime.setDeptName(taxorgname);
				}
				staytime.setTaxpayerCode(gasStationinfo.getTaxpayerCode());

			}

			if (records.size() > 0) {

				List<GasStaytimeResultExcel> gasStaytimeResultlList = new ArrayList<>();

				for (GasStaytimeResultEntity entity : records) {

					GasStaytimeResultExcel gasStaytimeResultExcel = GasStaytimeResultExcel.builder().id(entity.getId())
							.station(entity.getStation()).taxpayerCode(entity.getTaxpayerCode())
							.deptName(entity.getDeptName()).price(entity.getPrice()).oils(entity.getOils())
							.messageAppear(entity.getMessageAppear()).messageDisappear(entity.getMessageDisappear())
							.image(entity.getImage()).build();

					gasStaytimeResultlList.add(gasStaytimeResultExcel);

				}

				String fileName = TsBqUtils.getUUID() + ".xlsx";

				String excelPath = filePath + fileName;
				OutputStream out = null;

				try {
					out = new FileOutputStream(excelPath);
					ExcelWriter writer = EasyExcelFactory.getWriter(out);

					Sheet sheet1 = new Sheet(1, 0, GasStaytimeResultExcel.class);
					sheet1.setSheetName("数据");
					writer.write(gasStaytimeResultlList, sheet1);
					// 将上下文中的最终 outputStream 写入到指定文件中
					writer.finish();
					File excelFile = new File(excelPath);
					List<Object> excelFileInfo = new ArrayList<>();
					excelFileInfo.add(fileName);
					excelFileInfo.add(excelFile.length());
					excelFileInfo.add(fileUrl + "/" + fileName);

					// return DataResult.success(excelFileInfo);

					gasMineExportEntity.setFileName(fileName);
					gasMineExportEntity.setUrl(fileUrl + "/" + fileName);
					gasMineExportEntity.setSize(excelFile.length() + "");
					gasMineExportEntity.setState("2");
					gasMineExportEntity.setDescription("导出成功！");
					gasMineExportEntity.setUpdateTime(new Date());
					gasMineExportService.updateById(gasMineExportEntity);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
					// return DataResult.fail("xlsx生成失败：" + e.toString());
					gasMineExportEntity.setState("2");
					gasMineExportEntity.setDescription("xlsx生成失败：" + e.toString());
					gasMineExportEntity.setUpdateTime(new Date());
					gasMineExportService.updateById(gasMineExportEntity);
				} finally {
					try {
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
						/// return DataResult.fail("xlsx生成失败：" + e.toString());
						gasMineExportEntity.setState("2");
						gasMineExportEntity.setDescription("xlsx生成失败：" + e.toString());
						gasMineExportEntity.setUpdateTime(new Date());
						gasMineExportService.updateById(gasMineExportEntity);
					}

				}

			} else {
				// return DataResult.fail("暂无加油站停留数据！");
				gasMineExportEntity.setState("2");
				gasMineExportEntity.setDescription("暂无加油站停留数据！");
				gasMineExportEntity.setUpdateTime(new Date());
				gasMineExportService.updateById(gasMineExportEntity);
			}

		} else {
			/// return DataResult.fail("暂无加油站数据！");
			gasMineExportEntity.setState("2");
			gasMineExportEntity.setDescription("暂无加油站数据！");
			gasMineExportEntity.setUpdateTime(new Date());
			gasMineExportService.updateById(gasMineExportEntity);

		}

	}

	@ApiOperation(value = "查询分页数据")
	@PostMapping("/listhandle")
	// @RequiresPermissions("gasStaytimeResult:list")
	@ResponseBody
	public DataResult listhandle(@RequestBody GasStaytimeResultEntity gasStaytimeResult) throws ParseException {

		String currentDeptId = httpSessionService.getCurrentDeptId();

		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		String deptId = gasStaytimeResult.getDeptId();
		String stationName = gasStaytimeResult.getStationName();

		// 查询加油站
		LambdaQueryWrapper<GasStationinfoEntity> queryWrapperStationinfo = Wrappers.lambdaQuery();
		if (TsBqUtils.isNotNull(deptId)) {
			queryWrapperStationinfo.eq(GasStationinfoEntity::getType, "group");
			queryWrapperStationinfo.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			queryWrapperStationinfo.eq(GasStationinfoEntity::getTaxorgcode, deptId);

		} else {
			if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 县区局
				queryWrapperStationinfo.eq(GasStationinfoEntity::getType, "group");
				queryWrapperStationinfo.eq(GasStationinfoEntity::getIsAnalyse, "Y");
				queryWrapperStationinfo.eq(GasStationinfoEntity::getTaxorgcode, currentDeptId);

			} else if (Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 市局
				queryWrapperStationinfo.eq(GasStationinfoEntity::getType, "group");
				queryWrapperStationinfo.eq(GasStationinfoEntity::getIsAnalyse, "Y");
				queryWrapperStationinfo.like(GasStationinfoEntity::getTaxorgcode, currentDeptId.substring(0, 5));

			} else {
				// 省局
				queryWrapperStationinfo.eq(GasStationinfoEntity::getType, "group");
				queryWrapperStationinfo.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			}
		}

		if (TsBqUtils.isNotNull(stationName)) {
			queryWrapperStationinfo.like(GasStationinfoEntity::getName, stationName);
		}

		List<GasStationinfoEntity> listGasStationinfo = gasStationinfoService.list(queryWrapperStationinfo);
		List<String> stationinfoIdList = new ArrayList<>();
		for (GasStationinfoEntity stationinfo : listGasStationinfo) {
			String stationinfoId = stationinfo.getId();
			stationinfoIdList.add(stationinfoId);
		}

		if (TsBqUtils.isNotNull(stationinfoIdList)) {

			if (TsBqUtils.isNull(gasStaytimeResult.getCreateTimeStart())) {
				return DataResult.success("start-MessageDisappear不能为空！"); 
			}
			if (TsBqUtils.isNull(gasStaytimeResult.getCreateTimeEnd())) {
				return DataResult.success("end-MessageDisappear不能为空！");
			}
			
			gasStaytimeResult.setCreateTimeStart(gasStaytimeResult.getCreateTimeStart() + " 00:00:00");
			gasStaytimeResult.setCreateTimeEnd(gasStaytimeResult.getCreateTimeEnd() + " 23:59:59");
			gasStaytimeResult.setDeleted(0);

			int _page = gasStaytimeResult.getPage();
			int _limit = gasStaytimeResult.getLimit();

			if ((_page - 1) >= 1) {
				gasStaytimeResult.setPage((_page - 1) * _limit);
			} else {
				gasStaytimeResult.setPage(1);
			}

			List<GasStaytimeResultEntity> records = gasStaytimeResultService.listLimit(stationinfoIdList,
					gasStaytimeResult);
			List<GasStaytimeResultEntity> count = gasStaytimeResultService.listCount(stationinfoIdList,
					gasStaytimeResult);

			int total = 0;
			for (GasStaytimeResultEntity gasStaytimeResultEntity : count) {
				String _count = gasStaytimeResultEntity.getCount();
				total += Integer.parseInt(_count);

			}

			IPage<GasStaytimeResultEntity> _iPage = new Page<GasStaytimeResultEntity>();
			int size = gasStaytimeResult.getLimit();
			if (total == 0) {
				_iPage.setPages(1);
			} else {
				BigDecimal a = new BigDecimal(total); // 被除数
				BigDecimal b = new BigDecimal(size); // 除数
				// 将除数乘以10，并保持小数点位置不变，以进一位
				BigDecimal adjustedDivisor = b.multiply(BigDecimal.TEN);
				// 执行除法
				BigDecimal result = a.divide(adjustedDivisor);
				_iPage.setPages(result.longValue());
			}

			_iPage.setCurrent(gasStaytimeResult.getPage());
			_iPage.setRecords(records);
			_iPage.setSize(size);
			_iPage.setTotal(total);

			for (GasStaytimeResultEntity staytime : records) {
				GasStationinfoEntity gasStationinfo = gasStationinfoService.getById(staytime.getStationId());

				staytime.setStation(TsBqUtils.handleEndBeforeParentheses(gasStationinfo.getName()));
				String taxorgcode = gasStationinfo.getTaxorgcode();

				if (TsBqUtils.isNotNull(taxorgcode)) {
					String taxorgname = deptService.getById(taxorgcode).getName();
					staytime.setDeptName(taxorgname);
				}
			}
			return DataResult.success(_iPage);

		} else {
			return DataResult.fail("暂无加油站数据");
		}

	}

	@PostMapping("/delete")
	@ResponseBody
	public DataResult delete(@RequestBody List<GasStaytimeResultEntity> ids)
			throws java.io.IOException, ParseException {
		
		if(TsBqUtils.isNotNull(ids)){
			for (GasStaytimeResultEntity gasStaytimeResultEntity : ids) {
				String id = gasStaytimeResultEntity.getId();
				String messageDisappear = gasStaytimeResultEntity.getMessageDisappear();
				LambdaQueryWrapper<GasStaytimeResultEntity> queryWrapper = Wrappers.lambdaQuery();
				queryWrapper.eq(GasStaytimeResultEntity::getId, id);
				queryWrapper.eq(GasStaytimeResultEntity::getMessageDisappear, messageDisappear);
				gasStaytimeResultService.remove(queryWrapper);
			}
		}
		return DataResult.success();
	}

	@PostMapping("/download")
	@ResponseBody
	public DataResult download(@RequestBody List<GasStaytimeResultEntity> ids)
			throws java.io.IOException, ParseException {
		String zipName = TsBqUtils.getUUID();
		String zipNamePath = filePath + zipName + ".zip";
		String zipNameUrl = fileUrl + "/" +zipName + ".zip";
		
		List<Map<String, Object>> files = new ArrayList<>();

		for (GasStaytimeResultEntity entity : ids) {
			String _id = entity.getId();
			String _messageDisappear = entity.getMessageDisappear();
			LambdaQueryWrapper<GasStaytimeResultEntity> queryWrapper = Wrappers.lambdaQuery();
			queryWrapper.eq(GasStaytimeResultEntity::getId, _id);
			queryWrapper.eq(GasStaytimeResultEntity::getMessageDisappear, _messageDisappear);
			List<GasStaytimeResultEntity> list = gasStaytimeResultService.list(queryWrapper);
			// GasStaytimeResultEntity staytimeResultEntity = gasStaytimeResultService.getById(id);
			if (TsBqUtils.isNotNull(list)) {
				GasStaytimeResultEntity staytimeResultEntity = list.get(0);
				String stationId = staytimeResultEntity.getStationId();
				GasStationinfoEntity stationinfoEntity = gasStationinfoService.getById(stationId);
				String stationinfoName = stationinfoEntity.getName();
				String messageDisappear = staytimeResultEntity.getMessageDisappear();

				String image = staytimeResultEntity.getImage();

				if (TsBqUtils.isNotNull(image)) {
					Map<String, Object> map = new HashMap<>();
					map.put("file", new File(image.replace(fileUrl, filePath)));
					map.put("name", TsBqUtils.handleEndBeforeParentheses(stationinfoName) + "_" + messageDisappear + "_" + TsBqUtils.getUUID()
							+ "."+TsBqUtils.getFilenameExtension(image.replace(fileUrl, "")));
					files.add(map);
				}
			}
		}

		File zipTmpFile = new File(zipNamePath);
		try {
			// 压缩包文件若已存在则删除原本的文件
			if (zipTmpFile.exists()) {
				zipTmpFile.delete();
			}
			// 不存在新建压缩文件
			zipTmpFile.createNewFile();
			// 去除jsp编译html首部的空白行。
			// FileOutputStream字节输出流超类 文件输出流是用于将数据写入到输出流File或一个FileDescriptor
			// 创建文件输出流
			FileOutputStream fous = new FileOutputStream(zipTmpFile);
			// ZipOutputStream压缩流
			// 此流用于以 ZIP
			// 文件格式写入文件，包括对压缩和未压缩条目的支持，也就是把文件打包成压缩文件，常用于附件下载（多文件下载），文件压缩存储。
			ZipOutputStream zipOut = new ZipOutputStream(fous);
			// 循环处理待压缩文件
			int size = files.size();
			for (int i = 0; i < size; i++) {
				Map<String, Object> map = files.get(i);
				File file = (File) map.get("file");
				String name = (String) map.get("name");
				// 将文件写入压缩流
				TsBqUtils.zipFile(file, zipOut, name);
			}
			// 关闭流
			zipOut.close();
			fous.close();

		} catch (IOException e) {
			e.printStackTrace();
			return DataResult.fail(e.getMessage());
		}
		return DataResult.success(zipNameUrl);
	}

	@PostMapping("/deleteReal")
	@ResponseBody
	public DataResult deleteReal(@RequestBody @ApiParam(value = "id集合") List<String> ids)
			throws java.io.IOException, ParseException {

		return DataResult.success();
	}
}
